package com.znxs.zuopao_c.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.znxs.zuopao_c.common.BaseResponse;
import com.znxs.zuopao_c.common.ErrorCode;
import com.znxs.zuopao_c.common.ResultUtils;
import com.znxs.zuopao_c.domain.Request.TeamAddRequest;
import com.znxs.zuopao_c.domain.Request.TeamJoinRequest;
import com.znxs.zuopao_c.domain.Request.TeamUpdateRequest;
import com.znxs.zuopao_c.domain.Team;
import com.znxs.zuopao_c.domain.User;
import com.znxs.zuopao_c.domain.UserTeam;
import com.znxs.zuopao_c.domain.dto.TeamQuery;
import com.znxs.zuopao_c.domain.vo.TeamUserVO;
import com.znxs.zuopao_c.exception.BusinessException;
import com.znxs.zuopao_c.service.TeamService;
import com.znxs.zuopao_c.service.UserService;
import com.znxs.zuopao_c.service.UserTeamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 组队接口
 *
 * @author znxs
 */
@RestController
@RequestMapping("/team")
@Api(tags = "组队接口")
@Slf4j
//@CrossOrigin(originPatterns = {"http://localhost:5173"})
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    @PostMapping("/add")
    @ApiOperation("添加队伍接口")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        if (teamAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 拿到登录用户信息
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        try {
            BeanUtils.copyProperties(team,teamAddRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }

    @PutMapping("/update")
    @ApiOperation("修改队伍接口")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest,HttpServletRequest request){
        if (teamUpdateRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest,loginUser);
        if (!result){
            throw new BusinessException(ErrorCode.SYS_ERROR,"修改失败");
        }
        return ResultUtils.success(true);
    }

    @GetMapping("/getOne/{id}")
    @ApiOperation("查询单个队伍接口")
    public BaseResponse<Team> getTeam(@PathVariable("id") long id){
        if (id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team==null){
            throw new BusinessException(ErrorCode.SYS_ERROR,"查询单个失败");
        }
        return ResultUtils.success(team);
    }


    @GetMapping("/list")
    @ApiOperation("查询所有队伍接口")
    public BaseResponse<List<TeamUserVO>> listTeam(TeamQuery teamQuery,HttpServletRequest request){
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        Boolean isAdmin = userService.isAdmin(request);

        List<TeamUserVO> teamList = teamService.listTeams(teamQuery,isAdmin);
        return ResultUtils.success(teamList);
    }




    @GetMapping("/list/page")
    @ApiOperation("查询所有队伍接口(分页查询)")
    public BaseResponse<Page<Team>> listTeamPage(TeamQuery teamQuery){
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 处理包装类转成实体类
        Team team = new Team();
        try {
            BeanUtils.copyProperties(team,teamQuery);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYS_ERROR,"分页查询失败");
        }
        QueryWrapper<Team> teamQueryQueryWrapper = new QueryWrapper<>();
        Page<Team> resultPage = teamService.page(new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize()), teamQueryQueryWrapper);
        return ResultUtils.success(resultPage);
    }

    @PostMapping("/join")
    @ApiOperation("加入队伍接口")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest,HttpServletRequest request){
        if (teamJoinRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest,loginUser);
        return ResultUtils.success(result);
    }

    @PutMapping("/exit/{teamId}")
    @ApiOperation("退出队伍接口")
    public BaseResponse<Boolean> exitTeam(@PathVariable("teamId") long teamId, HttpServletRequest request){
        if (teamId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.exitTeam(teamId,loginUser);
        return ResultUtils.success(result);
    }

    @DeleteMapping("/delete/{teamId}")
    @ApiOperation("删除队伍接口")
    public BaseResponse<Boolean> deleteTeam(@PathVariable("teamId") long teamId, HttpServletRequest request){
        if (teamId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(teamId,loginUser);
        return ResultUtils.success(result);
    }

    @GetMapping("/list/create")
    @ApiOperation("获取用户创建的队伍接口")
    public BaseResponse<List<TeamUserVO>> getUserCreateTeam(TeamQuery teamQuery,HttpServletRequest request){
        if (teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> userCreateTeams = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(userCreateTeams);
    }

    @GetMapping("/list/join")
    @ApiOperation("获取用户加入的队伍接口")
    public BaseResponse<List<TeamUserVO>> getUserJoinTeam(TeamQuery teamQuery,HttpServletRequest request){
        if (teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        // 根据用户id查询user_team表 获取用户加入的team_id
        userTeamQueryWrapper.eq("user_id",loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
        // 获取的userTeamList是 [[1,1],[1,2]]这样的  需要转成map <1,[1,2]> 这样
        Map<Long, List<UserTeam>> listMap = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList = new ArrayList<>(listMap.keySet());
        // 把条件放入
        teamQuery.setIdList(idList);
        // 查询
        List<TeamUserVO> userJoinTeams = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(userJoinTeams);
    }

    @GetMapping("/list/teamUser")
    @ApiOperation("获取队伍中人员接口")
    public BaseResponse<List<Long>> teamUser(Integer teamId){
        if (teamId<1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("team_id",teamId);
        List<Long> teamUserIds = userTeamService.list(userTeamQueryWrapper).stream().map(item -> item.getUserId()).collect(Collectors.toList());
        if (teamUserIds.size()<1){
            throw new BusinessException(ErrorCode.SYS_ERROR);
        }
        return ResultUtils.success(teamUserIds);
    }

}
